<template>
  <div class="tools-div">
    <el-button type="success" size="small" @click="dialogVisible = true">
      添 加
    </el-button>
  </div>

  <el-table :data="list" style="width: 100%">
    <el-table-column prop="name" label="品牌名称" />
    <el-table-column prop="logo" label="品牌图标" #default="scope">
      <img :src="scope.row.logo" width="50" />
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" />
    <el-table-column label="操作" align="center" width="200" #default="scope">
      <el-button type="primary" size="small" @click="editShow(scope.row)">
        修改
      </el-button>
      <el-button type="danger" size="small" @click="remove(scope.row.id)">
        删除
      </el-button>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <div class="demo-pagination-block">
    <el-pagination
      v-model:current-page="currentPage4"
      v-model:page-size="pageSize4"
      :page-sizes="[10, 20, 50, 100]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <!-- 弹出框添加 -->

  <el-dialog v-model="dialogVisible" title="添加或修改" width="30%">
    <el-form label-width="120px">
      <el-form-item label="品牌名称">
        <el-input v-model="brand.name" />
      </el-form-item>
      <el-form-item label="品牌图标">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8501/brand/file"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getsave">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!-- 弹出框2 -->
  <el-dialog v-model="dialogVisible1" title="添加或修改" width="30%">
    <el-form label-width="120px">
      <el-form-item label="品牌名称">
        <el-input v-model="brand1.name" />
      </el-form-item>
      <el-form-item label="品牌图标">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8501/brand/file"
          :show-file-list="false"
          :on-success="handleAvatarSuccess1"
          :before-upload="beforeAvatarUpload1"
        >
          <img v-if="imageUrl1" :src="imageUrl1" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updaree()">提交</el-button>
        <el-button @click="dialogVisible1 = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { brandlist, brandsave, branddelete, branupdate } from '@/api/brand'
import { Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'

const brand1 = ref({
  name: '',
  logo: '',
})

// 修改
function updaree() {
  branupdate(brand1.value)
    .then(res => {
      // 关闭弹出框
      dialogVisible1.value = false

      // 显示成功消息
      ElMessage.success('品牌信息已更新')

      // 刷新数据
      getData()
    })
    .catch(error => {
      // 处理错误情况
      ElMessage.error('更新失败')
    })
}

//进入修改
const editShow = row => {
  brand1.value = { ...row }
  imageUrl1.value = row.logo
  console.log(row)
  dialogVisible1.value = true
}
const dialogVisible1 = ref(false)

const imageUrl1 = ref('')
const handleAvatarSuccess1 = (response, uploadFile) => {
  imageUrl1.value = URL.createObjectURL(uploadFile.raw)
  // 图片路径
  brand1.value.logo = response.data
  console.log(response.data)
}

// 判断上传的图片是否合规
const beforeAvatarUpload1 = rawFile => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('你的图片格式不正确!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('你的图片太大了!')
    return false
  }
  return true
}

//删除
const remove = async id => {
  try {
    // 弹出确认对话框，等待用户的确认
    await ElMessageBox.confirm('此操作将永久删除该记录, 是否继续?', 'Warning', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 用户点击了“确定”，执行删除操作
    await branddelete(id) // 确保等待删除操作完成

    // 显示删除成功消息
    ElMessage.success('删除成功')

    // 刷新数据
    await getData() // 确保等待数据刷新完成
  } catch (error) {
    // 用户点击了“取消”或其他错误
    if (error === 'cancel') {
      ElMessage.info('操作已取消')
    } else {
      ElMessage.error('删除失败')
    }
  }
}

// 定义表格数据模型
const list = ref([
  // { "id": 1, "name": "华为", "logo": "http://139.198.127.41:9000/sph/20230506/华为.png" },
  // { "id": 2, "name": "小米", "logo": "http://139.198.127.41:9000/sph/20230506/小米.png" },
])

// 定义提交表单数据模型
const brand = ref({
  name: '',
  logo: '',
})
// 添加我们好的数据我们来进行添加
function getsave() {
  brandsave(brand.value).then(res => {
    console.log(res.data)
    dialogVisible.value = false
    getData()
  })
}
// 开关
const dialogVisible = ref(false)

// minio返回路径
const imageUrl = ref('')
const handleAvatarSuccess = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw)
  brand.value.logo = response.data
  console.log(response.data)
}

// 判断上传的图片是否合规
const beforeAvatarUpload = rawFile => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('你的图片格式不正确!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('你的图片太大了!')
    return false
  }
  return true
}

// 分页条数据模型
const total = ref(0)
const currentPage4 = ref(1)
const pageSize4 = ref(10)
const condition = ref({
  pageNum: currentPage4.value,
  pageSize: pageSize4.value,
})

// 分页换页
const handleSizeChange = val => {
  condition.value.pageSize = val
  getData()
}
const handleCurrentChange = val => {
  condition.value.pageNum = val
  getData()
}
// 后端查询的数据添加给我们的table表格
const getData = async () => {
  const data = await brandlist(condition.value)
  total.value = data.data.total
  list.value = data.data.records
  console.log(data.data.records)
}

// 初始化
onMounted(() => {
  getData()
})
</script>

<style scoped>
.avatar-uploader {
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
  position: relative;
}

.avatar-uploader:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader .avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
  /* Ensures the image fills the container and maintains aspect ratio */
}

.avatar-uploader .el-upload {
  width: 100%;
  height: 100%;
  position: absolute;
  top: 0;
  left: 0;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100%;
  height: 100%;
  text-align: center;
  line-height: 178px;
  /* Centers the icon vertically */
}

.table-avatar {
  width: 50px;
  height: 50px;
  object-fit: cover;
  /* Ensures the image maintains aspect ratio */
}
</style>
